package com.th.coupon.executor.impl;

import com.th.coupon.common.vo.CouponTemplateSdk;
import com.th.coupon.common.vo.SettlementInfo;
import com.th.coupon.constant.RuleFlag;
import com.th.coupon.executor.AbstractRuleExecutor;
import com.th.coupon.executor.RuleExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Collections;

/**
 * 满减优惠卷结算规则执行器
 * @author 涂航
 */
@Component
@Slf4j
public class AllminusExecutor extends AbstractRuleExecutor implements RuleExecutor {


    /**
     * 规则类型标记
     * @return
     */
    @Override
    public RuleFlag ruleConfig() {
        return RuleFlag.ALLMINUS_RULE;
    }

    /**
     * 优惠卷规则计算
     * @param info {@link SettlementInfo} 包含了选择的优惠卷
     * @return
     */
    @Override
    public SettlementInfo computeRule(SettlementInfo info) {
        //计算总价
        Double goodsSum = retain2Decimals(
                goodsCostSum(info.getGoodsInfos()), 2);
        //效验优惠卷是否可使用
        SettlementInfo settlementInfo = processGoodsTypeNatSatisfy(info, goodsSum);
        //如果不为空说明优惠卷不适合当前商品类型使用
        if(null != settlementInfo){
            log.debug("Allminus Template Is Not Match To GoodsType !");
            return settlementInfo;
        }

        CouponTemplateSdk templateSdk =
                info.getCouponAndTemplateInfos().get(0).getTemplateSdk();
        //达到基本金额
        Double base = Double.valueOf(templateSdk.getRule().getDiscount().getBase());
        //减去金额
        Double quota = Double.valueOf(templateSdk.getRule().getDiscount().getQuota());
        //如果不符合标准，则直接返回商品总价
        if(goodsSum < base){
            log.debug("Current Goods Cost Sum < Allminus Coupon Base !");
            info.setCost(goodsSum);
            info.setCouponAndTemplateInfos(Collections.emptyList());
            return info;
        }
        //计算使用优惠卷之后的价格 - 结算
        info.setCost(
                retain2Decimals((goodsSum - quota) > minCost() ? (goodsSum - quota) : minCost(),2)
        );
        log.debug("Use ManJian Coupon Make Cost From {} To {}",goodsSum,info.getCost());

        return info;
    }
}
